package com.example.javagobang.controller;

import com.example.javagobang.Service.UserService;
import com.example.javagobang.constant.Constants;
import com.example.javagobang.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public UserInfo login(String username, String password, HttpServletRequest request){
        //根据名字查询密码，进行密码的判断
        UserInfo userInfo = new UserInfo();
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            //返回一个空对象
            return userInfo;
        }
        //进行查询
        userInfo =  userService.selectByName(username);
        if(!password.equals(userInfo.getPassword())){
           return new UserInfo();
        }
        //说明密码匹配
        //没有会话创建会话
        HttpSession session = request.getSession(true);
        //设置常量类，修改字符串
        session.setAttribute(Constants.user,userInfo);
        return userInfo;
    }

    /**
     * 用户注册
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public UserInfo register(String username,String password){
        //防止名字重复，插入不成功
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setUsername(username);
            userInfo.setPassword(password);
            userService.insert(userInfo);
            return userInfo;
        }catch (org.springframework.dao.DuplicateKeyException e){
            return new UserInfo();
        }
    }
    /**
     * 用户再次登录，从session进行获取用户信息
     */
    @RequestMapping(value = "/userinfo",method = RequestMethod.GET)
    public UserInfo userInfo(HttpServletRequest request){
        try {
            //没有会话创建会话，有了，就不再进行创建
            HttpSession session = request.getSession(false);
            UserInfo userInfo =(UserInfo) session.getAttribute(Constants.user);
            UserInfo newUserInfo = userService.selectByName(userInfo.getUsername());
            return newUserInfo;
        }catch (NullPointerException e){
            return new UserInfo();
        }
    }
}
